package br.com.application.dao;

import br.com.application.pojos.Student;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DAOStudent {

	private SQLiteDatabase banco;
	
	public DAOStudent(SQLiteDatabase banco){
		this.banco = banco;
	}
	
	public Student getStudent(){
		Student student = null;
		String sql = "SELECT REGISTRATION, NAME, COURSE, PERIOD FROM STUDENTS;";
		try{
			Cursor c = banco.rawQuery(sql, null);
			student = new Student();
			while(c.moveToNext()){
				student.setRegistration(c.getString(0));
				student.setName(c.getString(1));
				student.setCourse(c.getInt(2));
				student.setPeriod(c.getInt(3));
			}
			c.close();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			banco.close();
		}
		return student;
	}
	
	public boolean hasStudent(){
		String sql = "SELECT COUNT(*) FROM STUDENTS;";
		try{
			Cursor c = banco.rawQuery(sql, null );
			while(c.moveToNext()){
				return true;
			}
			c.close();
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		finally{
			banco.close();
		}
		return false;
	}
	
	public boolean insert(Student student){
		
		String insert =  " INSERT INTO STUDENTS					 ";
			   insert += " (     								 ";
			   insert += " REGISTRATION, 						 ";
			   insert += " NAME,         						 ";
			   insert += " COURSE,      						 ";
			   insert += " PERIOD       						 ";
			   insert += " )           							 ";
			   insert += " VALUES        						 ";
			   insert += " (      		 						 ";
			   insert += "'"+student.getRegistration()+ "',		 ";
			   insert += "'"+student.getName()+ "',				 ";
			   insert += ""+student.getCourse()+ ",				 ";
			   insert += ""+student.getPeriod()+ "               ";
			   insert += " );     		                         ";
			   
			   try{
				   banco.execSQL(insert);
				   return true;
			   }catch (Exception e) {
				   e.printStackTrace();
				   return false;
			   }finally{
				   banco.close();
			   }
			   
	}
	
}
